package cn.tedu.icop.order.rabbit;
import cn.tedu.icop.order.config.RabbitConfiguration;
import cn.tedu.icop.order.context.OrderContext;
import cn.tedu.icop.order.dao.repository.OrderRepository;
import cn.tedu.icop.order.pojo.po.ChargingBillFailPO;
import cn.tedu.icop.order.pojo.po.ChargingBillSuccessPO;
import cn.tedu.icop.order.pojo.po.OrderMQPO;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;

/**
 * 消费死信队列的消息
 */
@Slf4j
@Component
public class RabbitMQOrderConsumer {
    @Autowired
    private OrderRepository orderRepository;
    @RabbitListener(queues = RabbitConfiguration.DEAD_LETTER_QUEUE_NAME)
    public void consumeChargingQueue(OrderMQPO orderMQPO, Message message, Channel channel) throws IOException {
        log.debug("消费死信队列消息:{}",orderMQPO);
        log.debug("检查自检结果:{}",orderMQPO);
        //...... 这里要执行数据库操作.....
        String orderNo = orderMQPO.getOrderNo();
        ChargingBillSuccessPO chargingBillSuccessPO =
                orderRepository.selectSuccessOrderByOrderNo(orderNo);
        if (chargingBillSuccessPO == null){
            log.debug("没有成功订单,订单:{}",orderNo);
            ChargingBillFailPO chargingBillFailPO =
                    orderRepository.selectFailOrderByOrderNo(orderNo);
            if(chargingBillFailPO==null){
                ChargingBillFailPO newChargingBillFailPO = new ChargingBillFailPO();
                newChargingBillFailPO.setBillId(orderNo);
                newChargingBillFailPO.setFailDesc("自检失败");
                orderRepository.saveFailOrder(newChargingBillFailPO);
                log.debug("自检失败,订单:{}",orderNo);
            }
        }
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        channel.basicAck(deliveryTag,true);
    }
}
